<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="user.currentVal"
          :name="user.currentKey"
          :label="user.currentLabel"
          :placeholder="user.currentLabel"
          :rules="[{ required: true, message: `请填写用户名${user.currentLabel}` }]"
      />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        确认修改
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">

import {useRoute} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugin/myAxios.js";
import {showFailToast, showSuccessToast, Toast} from "vant";
import {setCurrentState} from "../state/user";

const route = useRoute()

console.log(route.query)
console.log(route.params)

// 用vue3的东西，把变量包装为响应式的对象
const user = ref({
  currentVal: route.query.value,
  currentLabel: route.query.label,
  currentKey: route.query.key,
  "id": route.query.id
});

function isEmpty(obj: any){
  const reg = "^[ ]+$";
  const re = new RegExp(reg);
  if(typeof obj == "undefined" || obj == null || obj == "" || re.test(obj)){
    return true;
  }else{
    return false;
  }
}


const onSubmit = async () => {
  if (isEmpty(user.value.currentVal)) {
    showFailToast("请有效字符！")
  }
  console.log('submit');
 const result:any = await myAxios.post("/user/update", {
    [user.value.currentKey as string]: user.value.currentVal,
    "id": route.query.id
  }).then((resp)=>{
    return resp;
 })

  if (result.data) {
    console.log("修改成功")
    // 更新成功后修改user的状态
    setCurrentState(result.data)
    showSuccessToast({
      message: "修改成功"
    })

    // 返回之前的页面
    history.back()
  } else {
    console.log(result.msg)
    showFailToast({
      message: result.msg
    })
  }
};

</script>

<style scoped>

</style>